import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;

public class gui {
    JFrame frame;
    JPanel framePanel, resultsPanel;
    JTable table;
    JScrollPane sp;
    GridBagConstraints gbc = new GridBagConstraints();
    static final int HORIZONTAL = GridBagConstraints.HORIZONTAL;
    static final int VERTICAL = GridBagConstraints.VERTICAL;
    static final int BOTH = GridBagConstraints.BOTH;
    public gui() {
        frame = new JFrame("Draft Picker");
        framePanel = new JPanel();
        framePanel.setLayout(new GridBagLayout());
        frame.add(framePanel);
        DefaultTableModel model = new DefaultTableModel(new Object[][]
                                                        {{".5","Team A"},{".3","Team B"},{".2","Team C"}},
                                                        new String[]
                                                        {"Percentage","Team Name"});
        table = new JTable(model);
        table.removeEditor();
        sp = new JScrollPane(table);
        sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        sp.setMaximumSize(new Dimension(500, 250));
        sp.setPreferredSize(new Dimension(500, 250));
        addToGridbag(2, 1, 0, 0, .5, .5, BOTH, framePanel, sp);
        addToGridbag(2, 1, 0, 1, .1, .1, HORIZONTAL, framePanel, getButtonPanel());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setBackground(new Color(0,150,200));
        frame.pack();
        frame.setVisible(true);
    }

    private void addToGridbag(int width, int height, int x, int y,
                              double wx, double wy, int fill, JComponent container, JComponent child) {
        if(container.getLayout() instanceof GridBagLayout) {
            gbc.gridwidth = width;
            gbc.gridwidth = height;
            gbc.gridx = x;
            gbc.gridy = y;
            gbc.weightx = wx;
            gbc.weighty = wy;
            gbc.fill = fill;
            container.add(child,gbc);
        }
    }

    private void addToGridbagAnchor(int width, int height, int x, int y,
                                    double wx, double wy, int fill, int anchor, JComponent container, JComponent child) {
        if(container.getLayout() instanceof GridBagLayout) {
            gbc.gridwidth = width;
            gbc.gridwidth = height;
            gbc.gridx = x;
            gbc.gridy = y;
            gbc.weightx = wx;
            gbc.weighty = wy;
            gbc.fill = fill;
            gbc.anchor = anchor;
            container.add(child,gbc);
        }
    }

    private JPanel getResultsPanel(ArrayList<String> results) {
        System.out.println(results);
        resultsPanel = new JPanel();
        resultsPanel.setLayout(new GridBagLayout());
        resultsPanel.setBorder(BorderFactory.createEtchedBorder());
        addToGridbag(1, 1, 0, 0, .5, .5, VERTICAL,
                resultsPanel, new JLabel("<html><u>Draft Order</u></html>"));
        for(int i = 0; i < results.size(); i++) {
            addToGridbag(1, 1, 0, i + 1, .5, .5, VERTICAL,
                    resultsPanel, new JLabel("<html><b>" + (i + 1) + ".</b> " + results.get(i) + "</html>"));
        }
        resultsPanel.validate();
        resultsPanel.setBackground(new Color(0,150,200));
        return resultsPanel;
    }

    private JPanel getButtonPanel() {
        JButton addRow, deleteRow, lottery;

        addRow = new JButton("Add Row");
        addRow.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
               addRow();
            }
        });

        deleteRow = new JButton("Delete Row");
        deleteRow.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent actionEvent) {
                deleteRow();
            }
        });


        lottery = new JButton("Lottery!");
        lottery.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent actionEvent) {
                doLottery();
            }
        });
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout());
        buttonPanel.add(addRow);
        buttonPanel.add(deleteRow);
        buttonPanel.add(lottery);
        buttonPanel.setBackground(new Color(0,150,200));
        return buttonPanel;
    }

    private void addRow() {
        DefaultTableModel tableModel = (DefaultTableModel)(table.getModel());
        tableModel.addRow(new Object[]{"",""});
        table.setRowSelectionInterval(table.getRowCount() - 1, table.getRowCount() - 1);
        table.validate();
        sp.validate();
        sp.getViewport().setViewPosition(new Point(0,sp.getViewport().getView().getHeight()));
    }

    private void deleteRow() {
        DefaultTableModel tableModel = (DefaultTableModel)(table.getModel());
        tableModel.removeRow(table.getSelectedRow());
    }

    private void doLottery() {
        Map<Double, String> tableMap = new HashMap<Double, String>();
        ArrayList<String> teamOrder;
        for(int i = 0; i < table.getRowCount(); i++) {
            Vector v = new Vector();
            v.add(((DefaultTableModel)table.getModel()).getValueAt(i,0));
            v.add(((DefaultTableModel)table.getModel()).getValueAt(i,1));
            if(v.size() != 2) {
                JOptionPane.showMessageDialog(frame,"Something when horribly wrong when trying to read the table.");
                return;
            }
            try {
                tableMap.put(Double.valueOf((String)v.get(0)), (String)v.get(1));
                System.out.println(tableMap);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(frame,"Could not parse table values: "+e.getMessage());
            }
        }

        try {
            ProbabilityQueue pq = new ProbabilityQueue(tableMap);
            teamOrder = new ArrayList<String>();
            while(!(pq.isEmpty())) {
                teamOrder.add(pq.pullTeamFromQueue());
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(frame,"Could not calculate draft order: "+ e.getMessage());
            return;
        }

        addToGridbag(2,1,0,2,.1,.1,BOTH,framePanel,getResultsPanel(teamOrder));
        frame.validate();
    }
}

